import { Location } from '@angular/common';
import { Component, Injectable, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { UserService } from '@global/shared/user.service';
import { KeycloakService } from 'keycloak-iop';
import { CookiesService } from 'ng-zorro-iop';
import { FcsStatusService } from '../service/fcs-status.service';
import { Environment } from '../../environments/environment';

@Component({
  selector: 'app-fcs-service-open',
  templateUrl: './fcs-not-opened.component.html',
  styleUrls: ['./fcs-not-opened.component.less']
})
export class FcsNotOpenedComponent implements OnInit {
  isLoading = false;

  constructor(
    private router: Router,
    private location: Location,
    private cookieService: CookiesService,
    private userService: UserService,
    private keycloakService: KeycloakService,
    private fcsStatusService: FcsStatusService
  ) { }

  async ngOnInit() {
    // 已开通服务但直接访问路由的情况
    let userId = this.keycloakService.getParentAccount();
    let res = await this.fcsStatusService.checkFCSServiceState(userId);
    let fcsServiceIsOpened =
      (res.code === '0' || res.code === 0) &&
      (res.result.listSize !== '0' && res.result.listSize !== 0);
    if (fcsServiceIsOpened) {
      this.router.navigate(['/overview']);
    }
  }
  /**
   * 开通父账号 2019/09/03
   */
  openService(): void {
    let userId = this.keycloakService.getParentAccount();
    let token = sessionStorage.getItem('inspur_token') || '';
    let region = this.cookieService.getCookie('region');
    this.fcsStatusService
      .approveFcsService(userId, token,region)
      .then(res => {
        if (res) {
          // console.log('res-openservice', res);
          if (res && res.result) {
            let key = res.result;
            // window.location.href = OSSEnvironment.url.commitOrder + '/' + key;
            window.location.href =
              Environment.application.bssFront + '/order/confirm/' + key.key;
          } else {
            console.log('no res.result.key found, res:', res);
          }
        }
      });
  }

  backToPreviousPage(): void {
    // 回退到访问前页面
    this.location.back();
  }

  productDetail(): void {
    window.open(Environment.application.productDocument + 'oss/index.html');
  }
}
